// 本模块要求的基础权限在index.js中定义为crm模块权限，即用户roles中具有crm-xxx，具体到每一个API接口所需要的权限，则应该在每个函数中去考查，例如某个用户是否可以查看某条记录
const express = require("express");
const eae = require("express-async-errors");
const router = express.Router();

const moment = require("moment");
const rds = require("./rds");
const tutils = require("./tutils");
const logger = require("./logger");
const dbq = require("./dbq");
const task = require("./task");

// GET 请求资源，查询单一user_profile，用re.params带入参数
router.get("/user-profile/:id", async (req, res) => {
    const totemUID = req.session.user?.uid;
    const { id } = req.params;
    const query = `SELECT * FROM eb_user_profile WHERE id = ? order by id desc`;
    const userProfiles = await dbq.queryUserProfiles(query, [id]);
    res.status(200).json({ userProfiles: userProfiles });
});

// GET 请求资源, 查询多条user_profiles, 用req.query带入参数
router.get("/user-profiles", async (req, res) => {
    const totemUID = req.session.user?.uid;
    const { uid } = req.query;
    const query = `SELECT * FROM eb_user_profile WHERE uid = ? and is_hide = 0 order by id desc`;
    const userProfiles = await dbq.queryUserProfiles(query, [uid]);
    res.status(200).json({ userProfiles: userProfiles });
});

// POST 创建资源, PUT 更新资源
router.post("/user-profile", async (req, res) => {
    const atype = "user";
    const totemUID = req.session.authUserInfo.totemUID;
    const type = `${req.session.crmROLE}_report`;
    const { uid, memo, attachmentUrls, confidentiality, task_id } = req.body;
    const title = `${moment().format("YYYY-MM-DD")} 信息更新 U#${totemUID}`;

    const query =
        "INSERT INTO tutem_mall.eb_user_profile (uid, atype, aid, type, title, memo, confidentiality, attachment_urls, add_time, task_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, UNIX_TIMESTAMP(), ?)";
    const queryResult = await rds.query(query, [
        uid,
        atype,
        totemUID,
        type,
        title,
        memo,
        confidentiality,
        JSON.stringify(attachmentUrls),
        task_id,
    ]);
    if (queryResult && task_id > 0) {
        const newRecordId = queryResult[0]?.insertId;
        const resultLink = `https://totemlife.cn/apps/crm/disclose-user-info?uid=${uid}`;
        const updateQuery = `update tutem_mall.tasks set status = 'finished', result = ? where assignee_uid = ${totemUID} and status != 'finished' and id = ${task_id}`;
        const [updateResult] = await rds.query(updateQuery, [resultLink]);
        if (updateResult?.affectedRows > 0) {
            //如果未实际更新，说明已经在这个任务下完成过一次了
            rds.query(
                `update tutem_mall.tasks set notified_count = notified_count + 1 where id = ${task_id}`
            ); //此处甩下即走
            let text = `✅小伙伴，大事告成！\nU#${totemUID}的任务T#${task_id}完成啦！\n点下方链接前往参观\n ${resultLink}`;
            let mark = `#### ✅小伙伴，大事告成！\n<font color='green'>U#${totemUID}的任务T#${task_id}完成啦！</font>\n[【点这里前往参观】](${resultLink})`;
            task.notifyXiaoteng(totemUID, text);
            task.notifyWework(totemUID, mark);
            const [rows] = await rds.query(
                `select id, code, created_at from tutem_mall.tasks where id = ${task_id}`
            );
            const taskCode = rows[0]?.code;
            if (taskCode) {
                const pattern = /crep\-follow\-.*\-registration/;
                if (pattern.test(taskCode)) {
                    const createdAt = moment(rows[0].created_at);
                    const currentTime = moment();
                    const diffHours = currentTime.diff(createdAt, "hours");
                    if (diffHours <= 24) {
                        //代表更新渠道用户的推荐信息
                        const [users] = await rds.query(
                            `select uid, spread_uid from tutem_mall.eb_user where uid = ${uid}`
                        );
                        const clientUID = users[0]?.spread_uid;
                        if (clientUID) {
                            if (clientUID != totemUID) {
                                tutils.grantTubay(
                                    clientUID,
                                    `task_id#${task_id}`,
                                    `${taskCode} award for client`,
                                    10.0,
                                    `${taskCode} award for client`
                                );
                                tutils.grantTubay(
                                    totemUID,
                                    `task_id#${task_id}`,
                                    `${taskCode} award for crep`,
                                    2.0,
                                    `${taskCode} award for crep`
                                );
                                mark = `#### 发放提醒\n ✅已向推荐人UID${clientUID}发放10枚图贝！\n ✅已向跟进人UID${totemUID}发放2枚图贝！\n`;
                            } else {
                                tutils.grantTubay(
                                    totemUID,
                                    `task_id#${task_id}`,
                                    `${taskCode} award for crep`,
                                    2.0,
                                    `${taskCode} award for crep`
                                );
                                mark = `#### 发放提醒\n 🚫推荐人与跟进人UID相同，不发放图贝！\n ✅已向跟进人UID${totemUID}发放2枚图贝！\n`;
                            }
                            task.notifyWework(totemUID, mark);
                        }
                    }
                }
            }
        }
    }
    res.status(201).json({ message: "User profile added successfully" });
});

//接收创建销售线索表数据入口
router.post("/create-sales-lead", async (req, res) => {
    const data = req.body; // 获取表单提交的数据
    console.log("create-sales-lead data:", data);
    const uid = req.session.totemUID; // 获取当前用户的UID
    let result = { errcode: 40001, errmsg: `功能只对内测用户开放`, id: 0 };
    if (uid !== 1) return res.json(result);
    result = { errcode: 0, errmsg: `创建成功，纪录ID为`, id: 0 };
    return res.jons(result);

    /*
    const query = `INSERT INTO sales_leads (creator_uid, follower_uid, stage, ...) VALUES (?, ?, ?, ...)`;
    try {
        await connection.query(query, [uid, data.follower, data.stage, ...]);
        res.status(201).send('Sales lead created successfully');
    } catch (error) {
        console.error('Error creating sales lead:', error);
        res.status(500).send('Server error');
    }
    */
});

module.exports = router;
